package com.hst.web.base.proxy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.hst.core.Page;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.meta.MetaData;
import com.hst.core.meta.proxies.DefaultDataProxy;
import com.hst.web.auth.po.User;
import com.hst.web.base.entity.TCompanyDept;
import com.hst.web.base.service.UserRoleService;
import com.hst.web.base.ui.CompanyDept;
import com.hst.web.sys.entity.TRole;

public class CompanyDeptProxy extends DefaultDataProxy {

	@Autowired
	IORDao dao;
	
	@Autowired
	UserRoleService us;

	@Override
	public Page<?> list(Map<String, ?> query, int pageIdx) {
		List<ORQuery> querys = parseQuery(query);
		User u = (User) ServiceContext.getInstance().getUser();
		TRole role = us.userRole(u.getId());
		if("2".equals(role.getRoleLevel())) {
			querys.add(new ORQuery(Op.eq, "companyCode", u.getCompanyCode()));
		}
		return dao.list(TCompanyDept.class, querys, pageIdx);
	}
	
	@Override
	public List<?> list(Map<String, ?> query) {
		List<ORQuery> querys = parseQuery(query);
		User u = (User) ServiceContext.getInstance().getUser();
		TRole role = us.userRole(u.getId());
		if("2".equals(role.getRoleLevel())) {
			querys.add(new ORQuery(Op.eq, "companyCode", u.getCompanyCode()));
		}
		return dao.list(TCompanyDept.class, querys);
	}
	

	@Override
	public Object save(MetaData data) throws Exception {
		CompanyDept data0 = (CompanyDept) data;
		List<TCompanyDept> depts = null;
		if(StringUtils.isEmpty(data0.getCompanyCode())) {
			User u = (User) ServiceContext.getInstance().getUser();
			data0.setCompanyCode(u.getCompanyCode());
		}
		//校验是否有重复的部门编码
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"companyCode",data0.getCompanyCode()));
		querys.add(new ORQuery(Op.eq,"code",data0.getCode()));
		if(0 == data.getOp()) {
			querys.add(new ORQuery(Op.neq,"deptCode",data0.getDeptCode()));
		}
		depts = dao.list(TCompanyDept.class,querys);
		if(depts.size() > 0) {
			throw new Exception("同一企业下部门编号不能重复");
		}
		//校验是否有重复的部门名称
		querys.clear();
		querys.add(new ORQuery(Op.eq,"companyCode",data0.getCompanyCode()));
		querys.add(new ORQuery(Op.eq,"deptName",data0.getDeptName()));
		if(0 == data.getOp()) {
			querys.add(new ORQuery(Op.neq,"deptCode",data0.getDeptCode()));
		}
		depts = dao.list(TCompanyDept.class,querys);
		if(depts.size() > 0) {
			throw new Exception("同一企业下部门名称不能重复");
		}		
		return super.save(data0);
	}
}
